<?php

namespace catchAdmin\phone\controller;

use catchAdmin\login\request\LoginRequest;
use catchAdmin\vr\model\Videos;
use catcher\base\CatchController;

use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\library\client\Response;
use EasyWeChat\Factory;
use thans\jwt\facade\JWTAuth;
use think\facade\Db;

//use catchAdmin\phone\common\Jwt as j;

class login extends CatchController
{
    protected $appid = 'wxf83cea5b79f3f035';
    protected $appsecret = 'cfc2e5f1ad013df9ded7330f668ee557';


    /**
     * 登陆
     *
     * @time 2019年11月28日
     * @param LoginRequest $request
     * @param CatchAuth $auth
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {

        $config = [
            'app_id' => $this->appid,
            'secret' => $this->appsecret,

        ];

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $userid = Db::name('wxuser')->where('openid', $user['id'])->find();

        if (empty($userid)) {  //无用户 插入一条1234

            Db::name('wxuser')->insertGetId([
                'avatar' => $user['avatar'],
                'openid' => $user['id'],
                'name' => $user['name'],
                'nickname' => $user['nickname'],
                'lasttime' => date('Y-m-d H:i:s', time())
            ]);

        } else {
            Db::name('wxuser')->where('openid', $user['id'])->update(['lasttime' => date('Y-m-d H:i:s', time())]);
        }

        $token = JWTAuth::builder(['0' => $user['id']]);
//
        return CatchResponse::success([
            'token' => $token,
        ], '登录成功');
//        try {
//
//            JWTAuth::auth();
//
//
//        } catch (\Exception $exception) {
//
//            echo 123;
//        }    }

    }
}